package face.unisannio.content;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

public class StudentDB {

	private static final String STUDENT_TABLE = "students";
	public static final String STUDENT_ID = "_id";
	public static final String STUDENT_NOME = "nome";
	public static final String STUDENT_COGNOME = "cognome";
	public static final String STUDENT_CLASSE = "classe";
	public static final String STUDENT_LABEL = "label";
	public static final String STUDENT_UID = "uid";
	public static final Uri CONTENT_URI = Uri
			.parse("content://face.unisannio.content.FaceRecognition/students");
	private SQLiteDatabase sdb;
	private Context context;
	private DbHelper sdbhelper;
	private static final String DB_NAME = "studentdb"; // nome del database
	private static final int DB_VERSION = 1; // versione del database

	public StudentDB(Context ctx) {
		context = ctx;
		sdbhelper = new DbHelper(context, DB_NAME, null, DB_VERSION);
	}

	public boolean open() {
		sdb = sdbhelper.getWritableDatabase();
		sdbhelper.onCreate(sdb);
		return (sdb == null) ? false : true;
	}

	public void close() {
		sdb.close();
	}

	public String getTableName() {
		return STUDENT_TABLE;
	}

	// inserimento
	/**
	 * @param student
	 * @return -1 if error else the record id
	 */
	public Uri insertStudent(Student student) {
		ContentValues cv = new ContentValues();
		cv.put(STUDENT_NOME, student.getNome());
		cv.put(STUDENT_COGNOME, student.getCognome());
		cv.put(STUDENT_CLASSE, student.getClasse());
		cv.put(STUDENT_LABEL, student.getLabel());
		cv.put(STUDENT_UID, student.getUid());

		long id = sdb.insert(STUDENT_TABLE, null, cv);
		return Uri.parse(CONTENT_URI + "/" + id);
	}

	public long insert(ContentValues cv) {
		long id = checkPresence(cv);
		if (checkPresence(cv) > -1)
			return id;
		else {
			String nome, cognome, classe;
			nome = cv.getAsString(STUDENT_NOME);
			cognome = cv.getAsString(STUDENT_COGNOME);
			classe = cv.getAsString(STUDENT_CLASSE);
			String label = nome + " " + cognome + " [" + classe + "] ";
			String uid = removeSpaces(nome) + removeSpaces(cognome)
					+ removeSpaces(classe);
			cv.put(STUDENT_LABEL, label);
			cv.put(STUDENT_UID, uid);
			id = sdb.insert(STUDENT_TABLE, null, cv);
			// return Uri.parse(CONTENT_URI + "/" + id);
			return id;
		}
	}

	private long checkPresence(ContentValues cv) {
		String nome, cognome, classe;
		nome = cv.getAsString(STUDENT_NOME);
		cognome = cv.getAsString(STUDENT_COGNOME);
		classe = cv.getAsString(STUDENT_CLASSE);
		String selection = StudentDB.STUDENT_NOME + "= ? AND "
				+ StudentDB.STUDENT_COGNOME + "=? AND "
				+ StudentDB.STUDENT_CLASSE + "= ?";
		String[] selectionArgs = { nome, cognome, classe };
		Cursor c = sdb.query(STUDENT_TABLE, null, selection, selectionArgs,
				null, null, null);
		((Activity) context).startManagingCursor(c);
		if (c.getCount() > 0) {
			c.moveToFirst();
			c.moveToFirst();
			String id = c.getString(c.getColumnIndex(StudentDB.STUDENT_ID));
			return Long.parseLong(id);
		} else
			return -1;
	}

	private String removeSpaces(String s) {
		StringTokenizer st = new StringTokenizer(s, " ", false);
		String t = "";
		while (st.hasMoreElements())
			t += st.nextElement();
		return t;
	}

	public List<Student> getStudents() {
		Cursor c = this.fetchStudents();
		return createStudentList(c);
	}

	public Cursor query(String[] columns, String selection,
			String[] selectionArgs, String groupBy, String having,
			String orderBy) {
		return sdb.query(STUDENT_TABLE, columns, selection, selectionArgs,
				groupBy, having, orderBy);
	}

	public String[] getStringArray(String columnName) {
		return getStringArray(columnName, null, null, null, null, null);
	}

	public String[] getStringArray(String columnName, String params,
			String[] paramsArg, String groupBy, String having, String orderBy) {
		String[] projection = { columnName };
		Cursor c = sdb.query(STUDENT_TABLE, projection, params, paramsArg,
				groupBy, having, orderBy);
		((Activity) context).startManagingCursor(c);
		int size = c.getCount();
		String[] array = new String[size];
		if (size > 0) {
			c.moveToFirst();
			int i = 0;
			while (!c.isAfterLast()) {
				array[i++] = c.getString(c.getColumnIndex(columnName));
				c.moveToNext();
			}
		}
		return array;

	}

	public SQLiteDatabase getSQLiteDatabase() {
		return sdb;
	}

	public int deleteStudent(String where, String[] whereArgs) {
		int res = sdb.delete(STUDENT_TABLE, where, whereArgs);
		return res;
	}

	public int updateStudent(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		int res = sdb.update(STUDENT_TABLE, values, selection, selectionArgs);
		return res;
	}

	public Cursor fetchStudents() { // metodo per fare la query di tutti i dati
		return sdb.query(STUDENT_TABLE, null, null, null, null, null, null);
	}

	// public Cursor query(String table, String[] columns, String selection,
	// String[] selectionArgs, String groupBy, String having, String orderBy){
	// return mdb.query(table, columns, selection, selectionArgs, groupBy,
	// having, orderBy);
	// }

	public void dump(File file) throws FileNotFoundException {
		Cursor c = fetchStudents();
		if (c.moveToFirst()) {
			Student curr = new Student(c.getString(c
					.getColumnIndex(StudentDB.STUDENT_NOME)), c.getString(c
					.getColumnIndex(StudentDB.STUDENT_COGNOME)), c.getString(c
					.getColumnIndex(StudentDB.STUDENT_CLASSE)), c.getString(c
					.getColumnIndex(StudentDB.STUDENT_LABEL)), c.getString(c
					.getColumnIndex(StudentDB.STUDENT_UID)));
			curr.write(file, false);
			c.moveToNext();
			while (!c.isAfterLast()) {
				curr = new Student(c.getString(c
						.getColumnIndex(StudentDB.STUDENT_NOME)), c.getString(c
						.getColumnIndex(StudentDB.STUDENT_COGNOME)), c.getString(c
						.getColumnIndex(StudentDB.STUDENT_CLASSE)), c.getString(c
						.getColumnIndex(StudentDB.STUDENT_LABEL)), c.getString(c
						.getColumnIndex(StudentDB.STUDENT_UID)));
				curr.write(file, true);
				c.moveToNext();
			}
		}
		c.close();
	}
	
	public int restore(File file) throws FileNotFoundException{
		ArrayList<Student> students=Student.read(file);
		ContentValues cv;
		int i=0;
		for (Student student : students) {
			cv=new ContentValues();
			cv.put(STUDENT_NOME, student.getNome());
			cv.put(STUDENT_COGNOME, student.getCognome());
			cv.put(STUDENT_CLASSE, student.getClasse());
			insert(cv);
			i++;
		}
		return i;
	}

	public String[] getColumnNames() {
		String[] res = new String[6];
		res[0] = STUDENT_ID;
		res[1] = STUDENT_NOME;
		res[2] = STUDENT_COGNOME;
		res[3] = STUDENT_CLASSE;
		res[4] = STUDENT_LABEL;
		res[5] = STUDENT_UID;
		return res;
	}

	public static List<Student> createStudentList(Cursor c) {
		List<Student> list = new ArrayList<Student>();
		Student current;
		c.moveToFirst();
		while (c.isAfterLast() == false) {
			current = new Student(c.getString(c.getColumnIndex(STUDENT_NOME)),
					c.getString(c.getColumnIndex(STUDENT_COGNOME)),
					c.getString(c.getColumnIndex(STUDENT_CLASSE)),
					c.getString(c.getColumnIndex(STUDENT_LABEL)), c.getString(c
							.getColumnIndex(STUDENT_UID)));
			list.add(current);
			c.moveToNext();
		}
		c.close();

		return list;
	}

	public void drop() {
		sdbhelper.drop(sdb);
	}

	private class DbHelper extends SQLiteOpenHelper { // utility per la
														// creazione del db

		private static final String STUDENTS_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " // codice
																							// sql
																							// di
																							// creazione
																							// della
																							// tabella
				+ STUDENT_TABLE
				+ " ("
				+ STUDENT_ID
				+ " integer primary key autoincrement, "
				+ STUDENT_NOME
				+ " text not null, "
				+ STUDENT_COGNOME
				+ " text not null, "
				+ STUDENT_CLASSE
				+ " text not null, "
				+ STUDENT_LABEL
				+ " text not null, " + STUDENT_UID + " text not null);";

		public DbHelper(Context context, String name, CursorFactory factory,
				int version) {
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(STUDENTS_TABLE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
			// TODO Auto-generated method stub
		}

		private void drop(SQLiteDatabase db) {
			db.execSQL("DROP TABLE " + STUDENT_TABLE);
		}

	}

}
